<template>
  <div class="operation">
    <a-spin tip="加载中..." :spinning="spinning">
      <div class="operation-search">
        <a-form layout="inline">
          <a-form-item label="制单日期：">
            <a-range-picker
              format="YYYY-MM-DD"
              :default-value="defaulttimeList"
              @change="onTime"
              v-model="defaulttimeList"
            >
              <template slot="dateRender" slot-scope="current">
                <div
                  class="ant-calendar-date"
                  :style="getcurrentStyle(current)"
                >
                  {{ current.date() }}
                </div>
              </template>
            </a-range-picker>
          </a-form-item>
          <a-form-item label="订单类型：">
            <a-select
              :allowClear="true"
              class="selectwidth"
              mode="multiple"
              v-model="searchItem.OrderType"
              placeholder="请选择"
            >
              <a-select-option
                v-for="item in DicType"
                :key="item.type"
                :value="item.type"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
          <a-form-item label="订单状态：">
            <a-select
              :allowClear="true"
              mode="multiple"
              :maxTagCount="1"
              class="selectwidth"
              v-model="searchItem.State"
              placeholder="请选择"
            >
              <a-select-option
                v-for="item in DicStatus"
                :key="item.type"
                :value="item.type"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
          <a-form-item label="订单号：">
            <a-input
              :allowClear="true"
              placeholder="请输入"
              v-model="searchItem.PackingPlanNo"
            />
          </a-form-item>
          <a-form-item label="物料编码：">
            <a-input
              :allowClear="true"
              placeholder="请输入"
              v-model="searchItem.MaterialCode"
            />
          </a-form-item>
          <a-form-item label="厂区：">
            <a-select
              :allowClear="true"
              mode="multiple"
              :maxTagCount="1"
              class="selectwidth"
              v-model="searchItem.WSType"
              placeholder="请选择"
              @change="handleChange"
            >
              <a-select-option
                v-for="item in WSTypeList"
                :key="item.type"
                :value="item.type"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
          <a-form-item label="车间：">
            <a-select
              :allowClear="true"
              class="selectwidth"
              v-model="searchItem.SegmentID"
              placeholder="请选择"
            >
              <a-select-option
                v-for="item in QSegmentList"
                :key="item.type"
                :value="item.type"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button
              class="default-button button-right-16"
              @click="GetPackingPlansListFun"
            >
              查询
            </a-button>
            <general-button
              @operation="SynchroMoveOrderFun"
              btnText="同步信息"
              btnPowerNum="BA1FC5DB-9DB2-47C8-BE42-921811F9C5AA"
            ></general-button>
          </a-form-item>
        </a-form>
      </div>
      <div class="table-box">
        <fieldset class="fieldset">
          <legend class="legend">
            <div style="font-size: 1rem">
              <a-icon type="snippets" theme="twoTone" /><span>订单列表 </span>
            </div>
          </legend>
          <div class="operation-table" id="id1">
            <div class="operation-table-box">
              <a-table
                :columns="columns"
                :rowClassName="rowClassName"
                :customRow="rowClick"
                :row-key="(record) => record.OrderID"
                :data-source="procedureData"
                :loading="loading"
                :scroll="{ x: 4200, y: heightid }"
                :pagination="false"
                size="small"
              >
                <template slot="OrderType" slot-scope="text, record">
                  {{
                    (DicType.find((o) => o.type === record.OrderType) || {})
                      .name
                  }}
                </template>
                <template slot="Status" slot-scope="text, record">
                  <!-- <span>{{ record.Status }}</span> -->
                  <span>{{ handPackingSatus(record.Status) }}</span>
                  <!-- <span v-if="record.Status == 0">ERP下达</span>
                <span v-else-if="record.Status == 1">待审核</span>
                <span v-else-if="record.Status == 2">下发执行</span>
                <span v-else-if="record.Status == 10">ERP反下达</span> -->
                </template>
                <template slot="IsCompleted" slot-scope="text, record">
                  <span>{{ record.IsCompleted ? "是" : "否" }}</span>
                </template>
                <template slot="action" slot-scope="text, record">
                  <div style="display: flex; justify-content: space-around">
                    <a-icon
                      type="search"
                      class="icon-class"
                      @click="OrderDetailShowFun(record)"
                    />
                  </div>
                </template>
              </a-table>
            </div>
            <div class="table-paging">
              <a-pagination
                show-size-changer
                :default-current="1"
                :pageSizeOptions="pageSizeOptions"
                :total="procedureTotal"
                :pageSize="searchItem.pageRequestModel.pageSize"
                @change="procedureChange"
                @showSizeChange="onShowSizeChange"
              />
            </div>
          </div>
        </fieldset>
      </div>
      <div class="table-boxbelow">
        <div class="boxleft">
          <fieldset
            class="fieldset"
            style="display: flex; flex-direction: column"
          >
            <legend class="legend">
              <div style="font-size: 1rem">
                <a-icon type="snippets" theme="twoTone" /><span
                  >计划单列表
                </span>
              </div>
            </legend>
            <div class="operation-table" id="id2">
              <div style="display: flex; flex-wrap: wrap">
                <general-button
                  style="margin: 5px 10px"
                  @operation="btnCreate"
                  btnText="新增"
                  btnPowerNum="4B7289D5-7B1A-47FF-B4FA-77583B46A0E0"
                  :btnDisabled="pplistsum()"
                ></general-button>
                <general-button
                  style="margin: 5px 10px"
                  @operation="btnEdit"
                  btnText="修改"
                  btnPowerNum="DA53A385-1521-4743-9FA5-51D1FD902570"
                  :btnDisabled="turnPermissions('保存')"
                ></general-button>
                <general-button
                  style="margin: 5px 10px"
                  @operation="btnSend"
                  btnText="下发"
                  btnPowerNum="26FDF952-4F61-4007-9E05-C8A982C8CA1E"
                  :btnDisabled="turnPermissions('下发')"
                ></general-button>
                <general-button
                  style="margin: 5px 10px"
                  @operation="btnClosePP"
                  btnText="关闭"
                  btnPowerNum="E3901D2A-421C-4971-B61A-9081B3074E50"
                  :btnDisabled="turnPermissions('关闭')"
                ></general-button>
                <general-button
                  style="margin: 5px 10px"
                  @operation="btnReplenishment"
                  btnText="补料"
                  btnPowerNum="74993096-BDF0-43BB-BD67-AFB4A8DBFA12"
                  :btnDisabled="turnPermissions('补料')"
                ></general-button>
                <general-button
                  style="margin: 5px 10px"
                  @operation="btnSendBack"
                  btnText="反下发"
                  btnPowerNum="2FD9AEF3-DC9F-48FC-A1D8-20E23C4F0C64"
                  :btnDisabled="turnPermissions('反下发')"
                ></general-button>

                <general-button
                  style="margin: 5px 10px"
                  @operation="btnSegment"
                  btnText="车间转移"
                  btnPowerNum="7D7C1CDC-3205-4431-91C9-AFA5F2DE73F5"
                  :btnDisabled="turnPermissions('车间转移')"
                ></general-button>
                <general-button
                  style="margin: 5px 10px"
                  @operation="btnPlanQty"
                  btnText="过程修改"
                  btnPowerNum="E2205708-5EFC-40EE-9280-1218380B44F7"
                  :btnDisabled="turnPermissions('过程修改')"
                ></general-button>

                <general-button
                  style="margin: 5px 10px"
                  @operation="btnReStartPP"
                  btnText="重启单据"
                  btnPowerNum="F479008A-CE29-4107-BCDB-FB218A742D42"
                  :btnDisabled="turnPermissions('重启单据')"
                ></general-button>
                <general-button
                  style="margin: 5px 10px"
                  @operation="btnMsutClosePP"
                  btnText="强制关闭单据"
                  btnPowerNum="7853D202-1397-406F-BFCD-9C9E7CA259E4"
                  :btnDisabled="turnPermissions('强制关闭')"
                ></general-button>
                <general-button
                  style="margin: 5px 10px"
                  @operation="btnPPRelation"
                  btnText="计划单关联"
                  btnPowerNum="4B7289D5-7B1A-47FF-B4FA-77583B46A0E0"
                  :btnDisabled="turnPermissions('计划单关联')"
                ></general-button>
              </div>
              <div class="operation-table-box">
                <a-table
                  :rowClassName="rowPPListClassName"
                  :customRow="rowPPListClick"
                  :columns="workunitcolumns"
                  :row-key="(record) => record.PackingPlanID"
                  :data-source="PPList"
                  :loading="loading1"
                  :scroll="{ x: 4800, y: heightids }"
                  :pagination="false"
                  size="small"
                >
                  <template slot="OrderType" slot-scope="text, record">
                    <span v-if="record.OrderTypeDes">{{
                      record.OrderTypeDes
                    }}</span>
                    <span v-else-if="record.OrderType == 10">灌装</span>
                    <span v-else-if="record.OrderType == 11">包装</span>
                    <span v-else-if="record.OrderType == 12">折叠</span>
                    <span v-else-if="record.OrderType == 13">冲裁</span>
                    <span v-else-if="record.OrderType == 14">无纺布生产</span>
                    <span v-else-if="record.OrderType == 15">挑选</span>
                    <span v-else-if="record.OrderType == 16">制袋</span>
                  </template>
                  <template slot="action" slot-scope="text, record">
                    <div style="display: flex; justify-content: space-around">
                      <a-icon
                        type="search"
                        class="icon-class"
                        @click="PPDetailShowFun(record)"
                      />
                    </div>
                  </template>
                </a-table>
              </div>
            </div>
          </fieldset>
        </div>
        <a-modal
          title="计划单信息"
          :visible="orderShow"
          @cancel="handleCancel"
          @ok="btnSave"
          :confirmLoading="spinningSave"
          width="70%"
          class="procedure-modal"
        >
          <div class="boxright">
            <fieldset class="fieldset fieldest-scroll">
              <legend class="legend">
                <div style="font-size: 1rem">
                  <a-icon type="snippets" theme="twoTone" /><span
                    >计划单信息
                  </span>
                </div>
              </legend>

              <div class="rowpad-box">
                <a-row class="rowpad">
                  <a-col :span="5"> <span>计划单号：</span></a-col>
                  <a-col :span="19">
                    <a-input
                      :allowClear="true"
                      placeholder="请输入"
                      v-model="selectedPPList.PackingPlanNo"
                  /></a-col>
                </a-row>
                <a-row class="rowpad">
                  <a-col :span="5"> <span>订单类型：</span></a-col>
                  <a-col :span="19">
                    <a-select
                      :disabled="isAdd"
                      :allowClear="true"
                      style="width: 100%"
                      v-model="selectedPPList.OrderType"
                      placeholder="请选择"
                    >
                      <a-select-option
                        v-for="item in packDicType"
                        :key="item.type"
                        :value="item.type"
                        >{{ item.name }}</a-select-option
                      >
                    </a-select>
                  </a-col>
                </a-row>
                <a-row class="rowpad">
                  <a-col :span="5"> <span>计划数量：</span></a-col>
                  <a-col :span="19">
                    <a-input-number
                      :min="1"
                      style="width: 100%"
                      v-model="selectedPPList.PlannedQuantity"
                  /></a-col>
                </a-row>
                <a-row class="rowpad">
                  <a-col :span="5"> <span>物料平衡上差值：</span></a-col>
                  <a-col :span="19">
                    <a-input-number
                      :min="0"
                      value="0"
                      style="width: 100%"
                      v-model="selectedPPList.UMaterialBalance"
                  /></a-col>
                </a-row>
                <a-row class="rowpad">
                  <a-col :span="5"> <span>物料平衡下差值：</span></a-col>
                  <a-col :span="19">
                    <a-input-number
                      :min="0"
                      style="width: 100%"
                      v-model="selectedPPList.LMaterialBalance"
                  /></a-col>
                </a-row>
                <a-row class="rowpad">
                  <a-col :span="5"> <span>厂区：</span></a-col>
                  <a-col :span="19">
                    <a-select
                      :allowClear="true"
                      style="width: 100%"
                      v-model="selectedPPList.WSType"
                      placeholder="请选择"
                      @change="handlePPlistChange"
                    >
                      <a-select-option
                        v-for="item in WSTypeList"
                        :key="item.type"
                        :value="item.type"
                        >{{ item.name }}</a-select-option
                      >
                    </a-select></a-col
                  >
                </a-row>
                <a-row class="rowpad">
                  <a-col :span="5"> <span>生产车间：</span></a-col>
                  <a-col :span="19">
                    <a-select
                      :allowClear="true"
                      style="width: 100%"
                      v-model="selectedPPList.SegmentID"
                      placeholder="请选择"
                      @change="handleSegmentIDChange"
                    >
                      <a-select-option
                        v-for="item in PPQSegmentList"
                        :key="item.type"
                        :value="item.type"
                        >{{ item.name }}</a-select-option
                      >
                    </a-select></a-col
                  >
                </a-row>
                <a-row class="rowpad">
                  <a-col :span="5"> <span>工艺：</span></a-col>
                  <a-col :span="19">
                    <a-select
                      v-model="selectedPPList.RouteID"
                      style="width: 100%"
                      :disabled="EditPPDis()"
                    >
                      <a-select-option
                        v-for="item in routerList"
                        :key="item.RouteID"
                      >
                        {{ item.RouteName }}({{ item.RouteVer }}){{
                          item.IfDefault ? "默认" : ""
                        }}
                      </a-select-option>
                    </a-select></a-col
                  >
                </a-row>
                <a-row class="rowpad">
                  <a-col :span="5"> <span>备注：</span></a-col>
                  <a-col :span="19">
                    <a-input
                      :allowClear="true"
                      placeholder="请输入备注"
                      v-model="selectedPPList.Remark"
                  /></a-col>
                </a-row>
              </div>
            </fieldset>
          </div>
        </a-modal>
      </div>
    </a-spin>

    <!--订单物料信息-->
    <OrderDetail
      :show.sync="OrderDetailShow"
      :procedureData="selectedprocedureData.ODList"
    ></OrderDetail>
    <!--计划单物料信息-->
    <PaRecipeDetail
      :show.sync="PPDetailShow"
      :procedureData="selectedPPList.PPDList"
    ></PaRecipeDetail>
    <!--计划单关联工单-->
    <PaRelation
      :show.sync="PPPaRelationShow"
      :bindorderList="selectedPPList.bindorderList"
      :selPackingPlan="selectedPPList"
    ></PaRelation>
    <!--车间转移-->
    <a-modal
      title="车间站点变更"
      :visible="EdtiSegmentshow"
      @ok="EdtiSegmentOk"
      :confirmLoading="spinningSave"
      @cancel="EdtiSegmentshow = false"
      width="30%"
      class="procedure-modal"
    >
      <a-row>
        <a-col :span="6"><span>生产车间</span></a-col>
        <a-col :span="18"
          ><a-select
            :allowClear="true"
            style="width: 100%"
            v-model="EdtiSegmentID"
            placeholder="请选择"
          >
            <a-select-option
              v-for="item in PPQSegmentList"
              :key="item.type"
              :value="item.type"
              >{{ item.name }}</a-select-option
            >
          </a-select></a-col
        >
      </a-row>
    </a-modal>
    <!--更改计划数量-->
    <a-modal
      title="修改"
      :visible="editPlanQtyShow"
      :confirmLoading="spinningSave"
      @ok="editPalnQty"
      @cancel="editPlanQtyShow = false"
      width="50%"
      class="procedure-modal"
    >
      <a-row class="rowpad">
        <a-col :span="7"><span>计划数量</span></a-col>
        <a-col :span="16"
          ><a-input-number
            :min="1"
            style="width: 100%"
            v-model="selectedPPList.PlannedQuantity"
        /></a-col>
      </a-row>
      <a-row class="rowpad">
        <a-col :span="7"> <span>工艺：</span></a-col>
        <a-col :span="16">
          <a-select
            v-model="selectedPPList.RouteID"
            style="width: 100%"
            :disabled="EditPPDis()"
          >
            <a-select-option v-for="item in routerList" :key="item.RouteID">
              {{ item.RouteName }}({{ item.RouteVer }}){{
                item.IfDefault ? "默认" : ""
              }}
            </a-select-option>
          </a-select></a-col
        >
      </a-row>
      <a-row class="rowpad">
        <a-col :span="7"> <span>物料平衡上偏差：</span></a-col>
        <a-col :span="16">
          <a-input-number
            :min="0"
            value="0"
            style="width: 100%"
            v-model="selectedPPList.UMaterialBalance"
        /></a-col>
      </a-row>
      <a-row class="rowpad">
        <a-col :span="7"> <span>物料平衡下偏差</span></a-col>
        <a-col :span="16">
          <a-input-number
            :min="0"
            style="width: 100%"
            v-model="selectedPPList.LMaterialBalance"
        /></a-col>
      </a-row>
    </a-modal>
    <!--计划单补料-->
    <a-modal
      title="计划单补料"
      :visible="Replenishmentshow"
      :confirmLoading="spinningSave"
      @ok="ReplenishmentOk"
      @cancel="Replenishmentshow = false"
      width="30%"
      class="procedure-modal"
    >
      <!-- 新增主物料选择框 -->
      <a-row v-if="false" class="rowpad">
        <a-col :span="6"><span>主物料:</span></a-col>
        <a-col :span="18">
          <a-select
            allowClear
            style="width: 100%"
            show-search
            v-model="Replenishmentdata.MainMaterialCode"
            @popupScroll="mainMaterialhandlepopupScroll"
            @search="mainMaterialSearch"
            @change="mainMaterialChange"
            @inputKeydown="inputMainKeydownFun"
          >
            <a-spin
              v-if="mainMaterialFetching"
              slot="notFoundContent"
              size="small"
            />
            <a-select-option
              v-for="(item, index) in mainMaterialsList"
              :value="item.MaterialCode"
              :key="index"
            >
              <span>{{ item.MaterialCode }}[{{ item.MaterialName }}]</span>
            </a-select-option>
          </a-select>
        </a-col>
      </a-row>
      <a-row class="rowpad">
        <a-col :span="6"><span>物料:</span></a-col>
        <a-col :span="18">
          <a-select
            style="width: 100%"
            show-search
            :value="materialsSearch.keyValue"
            v-model="Replenishmentdata.MaterialCode"
            @popupScroll="materialhandlepopupScroll"
            @search="materialSearch"
            @change="materialChange"
            @inputKeydown="inputKeydownFun"
          >
            <a-spin
              v-if="materialFetching"
              slot="notFoundContent"
              size="small"
            />
            <a-select-option
              v-for="(item, index) in materialsList"
              :value="item.MaterialCode"
              :key="index"
            >
              <span>{{ item.MaterialCode }}[{{ item.MaterialName }}]</span>
            </a-select-option>
          </a-select>
        </a-col>
      </a-row>
      <a-row class="rowpad">
        <a-col :span="6"><span>计量单位名称:</span></a-col>
        <a-col :span="18"
          ><a-input
            :allowClear="true"
            placeholder="请填写"
            style="width: 100%"
            v-model="Replenishmentdata.ComUnitName"
        /></a-col>
      </a-row>
      <a-row class="rowpad">
        <a-col :span="6"><span>需求数量:</span></a-col>
        <a-col :span="18"
          ><a-input-number
            :min="1"
            placeholder="请填写"
            style="width: 100%"
            v-model="Replenishmentdata.ReqQty"
        /></a-col>
      </a-row>
      <a-row class="rowpad">
        <a-col :span="6"><span>BOM比例:</span></a-col>
        <a-col :span="18"
          ><a-input-number
            :min="0"
            placeholder="请填写"
            style="width: 100%"
            v-model="Replenishmentdata.Ratio"
        /></a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
import moment from "moment";
import { getTableScroll } from "@/common/table-calc";
import {
  GetOrders,
  GetPLists,
  GetOrderDetails,
  GetPackingPlanDetails,
  SynchroMoveOrder,
  SavePacking,
  SendPacking,
  SendBackPacking,
  SegmentEditPacking,
  ClosePacking,
  ReStartPacking,
  ReplenishmentPacking,
  GetBindPackingPlanRelation,
  updPackingPlanByPlanQty,
} from "@/api/PackingPlanMange/index";
import { GetPackingPlanType } from "@/api/PackingPlanType-api/index";
import { getMaterials } from "@/api/MaterialManagement/index";
import { GetWorkShopTypesAll } from "@/api/WorkShopType/index";
import { GetSegments } from "@/api/NBCSegment/index";
import { debounce } from "@/common/debounce";
import OrderDetail from "./children/OrderDetail.vue";
import PaRecipeDetail from "./children/PaRecipeDetail.vue";
import PaRelation from "./children/PaRelation.vue";
import GeneralButton from "@/components/be-current-btn.vue";
import { getrouteListtomaterialCode } from "@/api/router-manage/index"; //查询产品工艺
//订单列表
const columns = [
  {
    title: "序号",
    dataIndex: "num",
    align: "center",
    fixed: "left",
  },
  {
    title: "订单号",
    dataIndex: "OrderCode",
    sorter: (a, b) => a.OrderCode.localeCompare(b.OrderCode),
    align: "center",
    width: 150,
    fixed: "left",
  },
  {
    title: "产品编码",
    dataIndex: "MaterialCode",
    align: "center",
    width: 120,
    fixed: "left",
  },
  {
    title: "产品名称",
    dataIndex: "MaterialName",
    align: "center",
    ellipsis: true,
    width: 230,
  },
  {
    title: "ERP配方",
    dataIndex: "ERecipeCode",
    align: "center",
    ellipsis: true,
    width: 150,
  },
  {
    title: "数量",
    dataIndex: "Qty",
    align: "center",
  },
  {
    title: "订单类型",
    dataIndex: "OrderType",
    align: "center",
    width: 100,
    scopedSlots: { customRender: "OrderType" }, //开启插槽
    sorter: (a, b) => Number(a.OrderType) - Number(b.OrderType),
  },
  {
    title: "订单状态",
    dataIndex: "Status",
    align: "center",
    scopedSlots: { customRender: "Status" }, //开启插槽
    sorter: (a, b) => Number(a.Status) - Number(b.Status),
  },
  {
    title: "制单日期",
    dataIndex: "CreateDate",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.CreateDate).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.CreateDate).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "计划开工日期",
    dataIndex: "PlanStartDt",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.PlanStartDt).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.PlanStartDt).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "计划完工日期",
    dataIndex: "PlanEndDT",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.PlanEndDT).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.PlanEndDT).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "是否已拆分",
    dataIndex: "IsCompleted",
    align: "center",
    scopedSlots: { customRender: "IsCompleted" }, //开启插槽
  },
  {
    title: "累计入库数量",
    dataIndex: "TotalQty",
    align: "center",
  },
  {
    title: "灌装日期",
    dataIndex: "FillingDt",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.FillingDt).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.FillingDt).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "创建人员",
    dataIndex: "CreateUser",
    align: "center",
  },
  {
    title: "创建时间",
    dataIndex: "CreateDt",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.CreateDt).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.CreateDt).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "修改人员",
    dataIndex: "ModifyUser",
    align: "center",
  },
  {
    title: "修改时间",
    dataIndex: "ModifyDt",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.ModifyDt).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.ModifyDt).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "关闭人员",
    dataIndex: "CloseUser",
    align: "center",
  },
  {
    title: "关闭时间",
    dataIndex: "CloseDt",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.CloseDt).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.CloseDt).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "挂起操作人",
    dataIndex: "HangupUser",
    align: "center",
  },
  {
    title: "挂起时间",
    dataIndex: "HangupDt",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.HangupDt).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.ModiHangupDtfyDt).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "操作",
    dataIndex: "operate",
    width: 100,
    align: "center",
    fixed: "right",
    scopedSlots: { customRender: "action" },
  },
];
//计划单列表
const workunitcolumns = [
  {
    title: "序号",
    dataIndex: "num",
    align: "center",
    fixed: "left",
  },
  {
    title: "计划单号",
    dataIndex: "PackingPlanNo",
    sorter: (a, b) => a.PackingPlanNo.localeCompare(b.PackingPlanNo),
    align: "center",
    width: 150,
    fixed: "left",
  },
  {
    title: "产品编码",
    dataIndex: "MaterialCode",
    align: "center",
    width: 120,
    fixed: "left",
  },
  {
    title: "产品名称",
    dataIndex: "MaterialName",
    align: "center",
    ellipsis: true,
    width: 230,
  },
  {
    title: "ERP配方",
    dataIndex: "ERecipeCode",
    align: "center",
    ellipsis: true,
    width: 150,
  },
  {
    title: "单据类型",
    dataIndex: "OrderTypeDes",
    width: 100,
    scopedSlots: { customRender: "OrderType" }, //开启插槽
    sorter: (a, b) => Number(a.OrderType) - Number(b.OrderType),
    align: "center",
  },
  {
    title: "计划数量",
    dataIndex: "PlannedQuantity",
    align: "center",
  },
  {
    title: "实际数量",
    dataIndex: "ActQuantity",
    align: "center",
  },
  {
    title: "取样数量",
    dataIndex: "SampleQty",
    align: "center",
  },
  {
    title: "不良数量",
    dataIndex: "BadQty",
    align: "center",
  },
  {
    title: "批次号",
    dataIndex: "BatchNo",
    align: "center",
  },
  {
    title: "工艺版本",
    dataIndex: "RouteVer",
    align: "center",
  },
  {
    title: "状态",
    dataIndex: "StateDesc",
    align: "center",
    sorter: (a, b) => a.StateDesc.localeCompare(b.StateDesc),
  },
  {
    title: "厂区",
    dataIndex: "WSName",
    align: "center",
  },
  {
    title: "车间",
    dataIndex: "SegmentName",
    align: "center",
  },
  {
    title: "计划开工时间",
    dataIndex: "PlanStartDt",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.PlanStartDt).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.PlanStartDt).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "计划完工时间",
    dataIndex: "PlanEndDt",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.PlanEndDt).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.PlanEndDt).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "生产日期",
    dataIndex: "ProductionDate",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.ProductionDate).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.ProductionDate).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "有效日期",
    dataIndex: "ExpiryDate",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.ExpiryDate).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.ExpiryDate).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "检验结果",
    dataIndex: "QMResult",
    align: "center",
  },
  {
    title: "报产上限比例",
    dataIndex: "ProductionRatio",
    align: "center",
  },
  {
    title: "备注",
    dataIndex: "Remark",
    align: "center",
  },
  {
    title: "下发人员",
    dataIndex: "AppointUser",
    align: "center",
  },
  {
    title: "下发时间",
    dataIndex: "AppointDt",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.AppointDt).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.AppointDt).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "创建人员",
    dataIndex: "CreateUser",
    align: "center",
  },
  {
    title: "创建时间",
    dataIndex: "CreateDt",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.CreateDt).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.CreateDt).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "修改人员",
    dataIndex: "ModifyUser",
    align: "center",
  },
  {
    title: "修改时间",
    dataIndex: "ModifyDt",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.ModifyDt).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.ModifyDt).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "关闭人员",
    dataIndex: "CloseUser",
    align: "center",
  },
  {
    title: "关闭时间",
    dataIndex: "CloseDt",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.CloseDt).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.CloseDt).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "挂起操作人",
    dataIndex: "HangupUser",
    align: "center",
  },
  {
    title: "挂起时间",
    dataIndex: "HangupDt",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.HangupDt).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.HangupDt).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "强制结束人员",
    dataIndex: "ForcedEndUser",
    align: "center",
  },
  {
    title: "强制结束时间",
    dataIndex: "ForcedEndDt",
    align: "center",
    sorter: (a, b) => {
      const aTime = new Date(a.ForcedEndDt).getTime(); // 需要先转换成时间戳
      const bTime = new Date(b.ForcedEndDt).getTime();
      return aTime - bTime;
    },
  },
  {
    title: "操作",
    dataIndex: "operate",
    width: 100,
    align: "center",
    fixed: "right",
    scopedSlots: { customRender: "action" },
  },
];
export default {
  name: "PackingPlanMange",
  components: {
    OrderDetail,
    PaRecipeDetail,
    PaRelation,
    GeneralButton,
  },
  data() {
    return {
      limits: {
        关闭: [0, 1, 2, 3, 4],
        下发: [0, 1],
        保存: [0, 1],
        强制关闭: [0, 1, 2, 3, 4],
        反下发: [2],
        补料: [2, 3, 4],
        车间转移: [2, 3, 4],
        重启单据: [5, 7],
        过程修改: [2, 3, 4],
        计划单关联: [0, 1, 2, 3, 4],
      },
      heightid: 0,
      heightids: 0,
      searchItem: {
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 30,
        },
        StartDt: null,
        EndDt: null,
        WSType: [],
        OrderType: [],
        State: [],
        SegmentID: null,
        MaterialCode: null,
        MaterialName: null,
        PackingPlanNo: null,
      }, //搜索
      pageSizeOptions: ["30", "50", "100", "200", "500", "1000"],
      procedureTotal: 0,
      loading: false, //表格loading
      columns,
      procedureData: [],
      selectedprocedureData: {},
      OrderDetailShow: false, //显示订单明细
      workunitcolumns,
      loading1: false, //表格loading
      PPList: [],
      selectedPPList: {},
      PPDetailShow: false, //显示罐装单明细明细
      defaulttimeList: [], //默认时间
      orderShow: false, //显示工单信息
      DicType: [
        {
          type: 1,
          name: "灌装",
        },
        {
          type: 2,
          name: "包装",
        },
        {
          type: 3,
          name: "折叠",
        },
        {
          type: 4,
          name: "冲裁",
        },
        {
          type: 5,
          name: "无纺布生产",
        },
        {
          type: 6,
          name: "挑选",
        },
        {
          type: 7,
          name: "制袋",
        },
      ],
      DicStatus: [
        {
          type: 0,
          name: "ERP下达",
        },
        {
          type: 10,
          name: "ERP反下达",
        },
        {
          type: 1,
          name: "待审核",
        },
        {
          type: 2,
          name: "下发执行",
        },
      ],
      packDicType: [
        {
          type: 10,
          name: "灌装",
        },
        {
          type: 11,
          name: "包装",
        },
        {
          type: 12,
          name: "折叠",
        },
        {
          type: 13,
          name: "冲裁",
        },
        {
          type: 14,
          name: "无纺布生产",
        },
        {
          type: 15,
          name: "挑选",
        },
        {
          type: 16,
          name: "制袋",
        },
      ],
      WSTypeList: [],
      QSegmentList: [],
      PPQSegmentList: [],
      AddPPModel: null, //新增单据
      spinningSave: false,
      EdtiSegmentID: null, //车间ID
      EdtiSegmentshow: false, //变更车间
      Replenishmentshow: false, //补料显示
      ReplenishmentconfirmLoading: false,
      Replenishmentdata: {}, //补料内容
      //物料搜索
      materialsList: [], //产品选择列表
      materialsNum: 0, //总条数
      editPlanQtyShow: false, //修改计划数量
      materialsSearch: {
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 30,
        },
        keyValue: "",
        ifLeafNode: true,
      }, //分页
      mainMaterialsSearch: {
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 30,
        },
        keyValue: "",
        ifLeafNode: true,
      }, //分页
      routeSearch: {
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 50,
        },
        keyWords: "",
        isCheck: true,
      }, //路由查询参数
      routerList: [], //工艺列表

      materialFetching: false,
      currentmaterialsInfo: {}, //当前选中的产品
      PPPaRelationShow: false, //计划单关联工单
      spinning: false, //加载
      isAdd: false, //是否新增
      mainMaterialsNum: 0, //总条数
      mainMaterialsList: [],
      mainMaterialFetching: false,
      currentMainMaterialsInfo: {}, //当前选中的产品
    };
  },
  methods: {
    //物料远程搜索
    materialSearch(value) {
      let that = this;
      that.materialsSearch.keyValue = value;
      // that.materialsSearch.pageRequestModel.pageIndex += 1;
      // that.materialFetching = true;
      // that.materialsList = [];
      // that.getmaterialsFun();
    },
    //键盘
    inputKeydownFun(e) {
      if (e.code == "Enter") {
        let that = this;
        // that.materialsSearch.keyValue = value;
        that.materialsSearch.pageRequestModel.pageIndex = 1;
        that.materialFetching = true;
        that.materialsList = [];
        that.getmaterialsFun();
      }
    },
    //键盘
    inputMainKeydownFun(e) {
      if (e.code == "Enter") {
        let that = this;
        // that.materialsSearch.keyValue = value;
        that.mainMaterialsSearch.pageRequestModel.pageIndex = 1;
        that.mainMaterialFetching = true;
        that.mainMaterialsList = [];
        that.getmainMaterialsFun();
      }
    },
    materialChange(value) {
      let that = this;
      that.currentmaterialsInfo = that.materialsList.find(
        (item) => item.MaterialCode == value
      );
      if (that.currentmaterialsInfo.MaterialName) {
        that.Replenishmentdata.MaterialName =
          that.currentmaterialsInfo.MaterialName;
        that.Replenishmentdata.MaterialCode =
          that.currentmaterialsInfo.MaterialCode;
      }
    },
    //查询产品
    getmaterialsFun: debounce(async function () {
      let that = this;
      const res = await getMaterials(that.materialsSearch);

      that.materialFetching = false;
      that.materialsList = that.materialsList.concat(res.Data.Data);
      that.materialsNum = res.Data.TotalNumber;
    }),
    //查询产品
    getmainMaterialsFun: debounce(async function () {
      let that = this;
      const res = await getMaterials(that.mainMaterialsSearch);

      that.mainMaterialFetching = false;
      that.mainMaterialsList = that.mainMaterialsList.concat(res.Data.Data);
      that.mainMaterialsNum = res.Data.TotalNumber;
    }),
    //下拉加载更多
    materialhandlepopupScroll(e) {
      let that = this;
      const { scrollHeight, scrollTop, clientHeight } = e.target;

      if (scrollHeight - scrollTop === clientHeight) {
        that.mainMaterialsSearch.pageRequestModel.pageIndex += 1;
        if (this.mainMaterialsList.length < that.mainMaterialsNum) {
          that.getmainMaterialsFun();
        }
      }
    },
    mainMaterialhandlepopupScroll(e) {
      let that = this;
      const { scrollHeight, scrollTop, clientHeight } = e.target;

      if (scrollHeight - scrollTop === clientHeight) {
        that.mainMaterialsSearch.pageRequestModel.pageIndex += 1;
        if (this.mainMaterialsList.length < that.mainMaterialsNum) {
          that.getmainMaterialsFun();
        }
      }
    },
    mainMaterialSearch(value) {
      let that = this;
      that.mainMaterialsSearch.keyValue = value;
    },
    mainMaterialChange(value) {
      let that = this;
      that.currentMainMaterialsInfo = that.mainMaterialsList.find(
        (item) => item.MaterialCode == value
      );
      if (that.currentMainMaterialsInfo.MaterialName) {
        that.Replenishmentdata.MainMaterialName =
          that.currentMainMaterialsInfo.MaterialName;
        that.Replenishmentdata.MainMaterialCode =
          that.currentMainMaterialsInfo.MaterialCode;
      }
    },
    //新增权限
    pplistsum() {
      let that = this;

      let sum = 0;
      that.PPList.map((i) => (sum += Number(i.PlannedQuantity)));
      if (JSON.stringify(that.selectedprocedureData) == "{}") {
        return true;
      }

      if (that.PPList.length == 0 || sum < that.selectedprocedureData.Qty) {
        return false;
      } else {
        return true;
      }

      // if (that.selectedprocedureData.Qty === sum) {
      //   return true;
      // }
      // return false;
    },
    //编辑权限
    EditPPDis() {
      let that = this;
      if (JSON.stringify(that.selectedPPList) !== "{}") {
        if (that.selectedPPList.State == 1) {
          return true;
        } else {
          return false;
        }
      }
      return false;
    },
    //关闭按钮权限
    turnPermissions(name) {
      //状态为0 1 2 3 4可操作
      let _this = this;
      if (JSON.stringify(_this.selectedPPList) !== "{}") {
        if (_this.limits[name].length > 0) {
          return !_this.limits[name].includes(_this.selectedPPList.State);
        }
      }
      return true;
    },
    //时间选择
    onTime(e, e1) {
      let that = this;
      that.searchItem.StartDt = that.dateExt.showDate(e[0]._d);
      that.searchItem.EndDt = that.dateExt.showDate(e[1]._d);
    },
    //时间选择器的样式填充
    getcurrentStyle(current, today) {
      const style = {};
      if (current.date() === 1) {
        style.border = "1px solid #1890ff";
        style.borderRadius = "50%";
      }
      return style;
    },
    //选中厂区
    handleChange(value) {
      let that = this;
      if (value) {
        that.GetSegmentsAllFun(that.searchItem.WSType, true);
      }
    },
    //选中厂区
    handlePPlistChange(value) {
      let that = this;
      if (value) {
        let WSType = [that.selectedPPList.WSType];
        sessionStorage.setItem("packwstype", that.selectedPPList.WSType);
        that.GetSegmentsAllFun(WSType);
      }
    },
    //选择车间
    handleSegmentIDChange(value) {
      let that = this;
      if (value) {
        sessionStorage.setItem("packsegmentid", that.selectedPPList.SegmentID);
      }
    },
    //工单状态
    handPackingSatus(value) {
      let result = "";
      switch (value) {
        case -2:
          result = "关闭";
          break;
        case -1:
          result = "ERP反下达";
          break;
        case 0:
          result = "ERP下达";
          break;
        case 1:
          result = "待审核";
          break;
        case 2:
          result = "已下发";
          break;
        case 3:
          result = "生产中";
          break;
        case 4:
          result = "开始出料";
          break;
        case 5:
          result = "结束出料";
          break;
        case 6:
          result = "生产结束";
          break;
        case 7:
          result = "强制关闭";
          break;
        case 8:
          result = "关闭";
          break;
        case 9:
          result = "关闭";
          break;
        case 10:
          result = "ERP返下达锁定";
          break;
        case 11:
          result = "ERP锁定";
          break;
        case 12:
          result = "ERP关闭";
          break;
        case 13:
          result = "ERP删除";
          break;
        default:
          result = "";
          break;
      }
      return result;
    },
    //获取工单类型
    async GetPackingPlanTypeFun() {
      let that = this;
      let res = await GetPackingPlanType();
      if (res.Status == 10000) {
        let wtList = [];
        res.Data.map((item) => {
          wtList.push({ type: item.EnumValue, name: item.PackingPlanTypeName });
        });
        that.DicType = wtList;
      } else {
        that.$message.error(res.Message);
      }
    },
    //获取厂区列表
    async GetWorkShopTypesAllFun() {
      let that = this;
      let res = await GetWorkShopTypesAll(10);
      if (res.Status == 10000) {
        let wtList = [];
        res.Data.map((item) => {
          wtList.push({ type: item.WSType, name: item.WSName });
        });
        that.WSTypeList = wtList;
      } else {
        that.$message.error(res.Message);
      }
    },
    //获取车间列表
    GetSegmentsAllFun: debounce(async function (WSType, ispplist = false) {
      let that = this;
      let SegSegmentID = [
        "1735FA0C-33E4-4B25-AAA2-DE084FB7D1E3",
        "5D494A1E-5F24-4036-9350-2E442A19FE87",
        "CCDB0114-7026-4218-A507-5C00E870B0B3",
        "12FF8C8D-B2DC-4554-AA9B-91703F4AB200",
        "0D3C49AA-BBB3-402A-B618-FBEBED4CC85E",
      ];
      //新建单据的时候，判断类型。只显示对应类型车间
      if (!ispplist && JSON.stringify(that.selectedPPList) !== "{}") {
        switch (that.selectedPPList.OrderType) {
          case 10: //灌包
            SegSegmentID = ["5D494A1E-5F24-4036-9350-2E442A19FE87"];
            break;
          case 11: //包装
            SegSegmentID = ["1735FA0C-33E4-4B25-AAA2-DE084FB7D1E3"];
            break;
          case 12: //折叠
            SegSegmentID = ["CCDB0114-7026-4218-A507-5C00E870B0B3"];
            break;
          case 13: //冲裁
          case 14: //无纺布
          case 15: //挑选
            SegSegmentID = ["12FF8C8D-B2DC-4554-AA9B-91703F4AB200"];
            break;
          case 16: //制袋
            SegSegmentID = ["0D3C49AA-BBB3-402A-B618-FBEBED4CC85E"];
            break;
          default:
            break;
        }
      }
      let res = await GetSegments({
        SegSegmentID: SegSegmentID,
        WSTypeList: WSType,
      });
      if (res.Status == 10000) {
        let wtList = [];
        res.Data.map((item) => {
          wtList.push({ type: item.SegmentID, name: item.SegmentName });
        });
        if (ispplist) {
          that.QSegmentList = wtList;
        } else {
          that.PPQSegmentList = wtList;
        }
      } else {
        that.$message.error(res.Message);
      }
    }),
    //隐藏计划单信息
    handleCancel() {
      this.orderShow = false;
    },
    checkRow(record) {
      if (this.selectedprocedureData.OrderID !== record.OrderID) {
        this.selectedprocedureData = record;
        this.GetPListFun();
        this.getrouteListtomaterialCodeFun();
      }
    },

    // 计划点击行时
    rowClick(record, index) {
      return {
        on: {
          click: (e) => {
            let row = JSON.parse(JSON.stringify(record));
            this.checkRow(row);
          },
        },
        style: {
          "background-color":
            record.OrderID === this.selectedprocedureData.OrderID
              ? "#e6f7ff"
              : "",
        },
      };
    },
    checkRowPPList(record) {
      this.routeSearch.keyWords = record.MaterialCode;

      if (
        this.selectedPPList.PackingPlanID !== record.PackingPlanID ||
        record.PackingPlanID === undefined
      ) {
        this.selectedPPList = record;
        this.GetSegmentsAllFun([this.selectedPPList.WSType]);
      }
    },
    // 计划明细点击行时
    rowPPListClick(record, index) {
      return {
        on: {
          click: (e) => {
            let row = JSON.parse(JSON.stringify(record));
            this.checkRowPPList(row);
          },
        },
        style: {
          "background-color":
            record.PackingPlanID === this.selectedPPList.PackingPlanID
              ? "#e6f7ff"
              : "",
        },
      };
    },
    //高亮行样式
    rowClassName(record, index) {
      return this.selectedprocedureData.OrderID == record.OrderID
        ? "checked-td-of-add-table"
        : " ";
    },
    rowPPListClassName(record, index) {
      return this.selectedPPList.PackingPlanID == record.PackingPlanID
        ? "checked-td-of-add-table"
        : " ";
    },
    //显示订单明细
    async OrderDetailShowFun(row) {
      let that = this;
      row.ODList = [];

      that.loading = true;
      let res = await GetOrderDetails({
        OrderID: row.OrderID,
      });
      if (res.Status == 10000) {
        res.Data.map((item, index) => {
          item.CreateDate = that.dateExt.showFullDate(item.CreateDate);
        });
        row.ODList = res.Data;
        that.selectedprocedureData.ODList = row.ODList;
        that.loading = false;
        that.OrderDetailShow = true;
      } else {
        that.$message.error(res.Message);
        that.loading = false;
      }
    },
    //显示计划单明细
    async PPDetailShowFun(row) {
      let that = this;
      if (row.PackingPlanID === undefined) return;
      row.PPDList = [];
      that.loading1 = true;
      let res = await GetPackingPlanDetails({
        PackingPlanID: row.PackingPlanID,
      });
      if (res.Status == 10000) {
        res.Data.map((item, index) => {
          item.NCreateDate = that.dateExt.showFullDate(item.NCreateDate);
        });
        row.PPDList = res.Data;
        that.loading1 = false;
        that.selectedPPList.PPDList = row.PPDList;
        that.PPDetailShow = true;
      } else {
        that.$message.error(res.Message);
        that.loading1 = false;
      }
    },
    //获取单据列表
    GetPackingPlansListFun: debounce(async function () {
      let that = this;

      that.selectedPPList = {};
      that.selectedprocedureData = {};
      that.loading = true;
      let res = await GetOrders(that.searchItem);
      if (res.Status == 10000) {
        res.Data.Data.map((item, index) => {
          item.num = index + 1;
          item.PlanStartDt = that.dateExt.showDate(item.PlanStartDt);
          item.PlanEndDT = that.dateExt.showDate(item.PlanEndDT);
          item.CreateDate = that.dateExt.showFullDate(item.CreateDate);
          item.CreateDt = that.dateExt.showFullDate(item.CreateDt);
          item.ModifyDt = that.dateExt.showFullDate(item.ModifyDt);
          item.CloseDt = that.dateExt.showFullDate(item.CloseDt);
          item.HangupDt = that.dateExt.showFullDate(item.HangupDt);
          item.FillingDt = that.dateExt.showFullDate(item.FillingDt);
        });
        that.procedureData = res.Data.Data;
        if (that.procedureData.length > 0) {
          that.checkRow(that.procedureData[0]);
        }
        that.procedureTotal = res.Data.TotalNumber;
        that.loading = false;
      } else {
        that.$message.error(res.Message);
        that.loading = false;
      }
    }),
    //获取单据详情列表
    GetPListFun: debounce(async function () {
      let that = this;
      that.PPList = [];
      that.AddPPModel = null;
      that.selectedPPList = {};
      that.loading1 = true;
      let res = await GetPLists({
        OrderID: that.selectedprocedureData.OrderID,
      });
      if (res.Status == 10000) {
        res.Data.map((item, index) => {
          item.num = index + 1;
          item.ProductionDate = that.dateExt.showDate(item.ProductionDate);
          item.ExpiryDate = that.dateExt.showDate(item.ExpiryDate);
          item.PlanStartDt = that.dateExt.showDate(item.PlanStartDt);
          item.PlanEndDt = that.dateExt.showDate(item.PlanEndDt);
          item.AppointDt = that.dateExt.showFullDate(item.AppointDt);
          item.CreateDt = that.dateExt.showFullDate(item.CreateDt);
          item.ModifyDt = that.dateExt.showFullDate(item.ModifyDt);
          item.CloseDt = that.dateExt.showFullDate(item.CloseDt);
          item.HangupDt = that.dateExt.showFullDate(item.HangupDt);
          item.ForcedEndDt = that.dateExt.showFullDate(item.ForcedEndDt);
          item.UMaterialBalance = item.UMaterialBalance ?? 0;
          item.LMaterialBalance = item.LMaterialBalance ?? 0;
        });
        that.PPList = res.Data;
        if (that.PPList.length > 0) {
          that.checkRowPPList(that.PPList[0]);
        }
        that.loading1 = false;
      } else {
        that.$message.error(res.Message);
        that.loading1 = false;
      }
    }),
    //同步生产计划接口表到MES生产计划表
    async SynchroMoveOrderFun() {
      let that = this;
      that.spinning = true;
      let res = await SynchroMoveOrder();
      if (res.Status == 10000) {
        that.$message.success(res.Data);
        that.GetPackingPlansListFun();
      } else {
        that.$message.error(res.Message);
      }
      that.spinning = false;
    },
    //切换页数
    procedureChange(page, pageSize) {
      this.searchItem.pageRequestModel.pageIndex = page;
      this.searchItem.pageRequestModel.pageSize = pageSize;
      this.GetPackingPlansListFun();
    },
    //切换条数
    onShowSizeChange(current, size) {
      this.searchItem.pageRequestModel.pageIndex = current;
      this.searchItem.pageRequestModel.pageSize = size;
      this.GetPackingPlansListFun();
    },
    //新增
    btnCreate() {
      let that = this;
      that.isAdd = true; //是否新增

      if (JSON.stringify(that.selectedprocedureData) == "{}") {
        that.$message.error("请选择订单");
        return;
      }
      //订单状态是(0初始)或(2下发执行中)才能拆分
      if (
        that.selectedprocedureData.Status != 0 &&
        that.selectedprocedureData.Status != 1 &&
        that.selectedprocedureData.Status != 2
      ) {
        that.$message.error("当前订单状态不能拆分订单！");
        return;
      }
      //只能新建一个空的
      if (that.AddPPModel) {
        that.$message.info("请先保存新建订单,再新建");
        return;
      }
      let NewNo = (that.PPList.length + 1).toString().PadLeft(2, "0");

      let sum = 0;
      //订单类型
      let OrderTypes = that.selectedprocedureData.OrderType;
      switch (that.selectedprocedureData.OrderType) {
        case 1:
          OrderTypes = 10;
          break;
        case 2:
          OrderTypes = 11;
          break;
        case 3:
          OrderTypes = 12;
          break;
        case 4:
          OrderTypes = 13;
          break;
        case 5:
          OrderTypes = 14;
          break;
        case 6:
          OrderTypes = 15;
          break;
        case 7:
          OrderTypes = 16;
          break;
        default:
          break;
      }
      that.PPList.map((i) => (sum += Number(i.PlannedQuantity)));
      that.AddPPModel = {
        num: that.PPList.length + 1,
        PackingPlanNo: that.selectedprocedureData.OrderCode,
        MaterialCode: that.selectedprocedureData.MaterialCode,
        PlanStartDt: that.selectedprocedureData.PlanStartDt,
        PlanEndDt: that.selectedprocedureData.PlanEndDT,
        OrderID: that.selectedprocedureData.OrderID,
        OrderType: OrderTypes,
        State: 0,
        WSType:
          that.isAdd == true && sessionStorage.getItem("packwstype")
            ? Number(sessionStorage.getItem("packwstype"))
            : that.selectedPPList.WSType,
        SegmentID:
          that.isAdd == true && sessionStorage.getItem("packsegmentid")
            ? sessionStorage.getItem("packsegmentid")
            : that.selectedPPList.SegmentID,
        PlannedQuantity: that.selectedprocedureData.Qty - sum,
        UMaterialBalance: that.selectedPPList.UMaterialBalance ?? 0,
        LMaterialBalance: that.selectedPPList.LMaterialBalance ?? 0,
        PlanIndex: that.PPList.length + 1,
        IfDefault: true,
        RouteID: null,
      };
      if (that.isAdd == true && sessionStorage.getItem("packwstype")) {
        that.GetSegmentsAllFun([sessionStorage.getItem("packwstype")]);
      }
      if (that.routerList.length > 0)
        that.routerList.forEach((item) => {
          if (item.IfDefault) {
            that.AddPPModel.RouteID = item.RouteID;
          }
        });
      that.PPList.push(that.AddPPModel);
      that.selectedPPList = that.PPList.find(
        (f) => f.PackingPlanID === undefined
      );
      that.orderShow = true;
    },
    //修改
    btnEdit() {
      this.orderShow = true;
      this.isAdd = false; //是否新增
    },
    //保存
    async btnSave() {
      let that = this;
      if (JSON.stringify(that.selectedPPList) == "{}") {
        that.$message.error("请选择计划单！");
        return;
      }
      if ((that.selectedPPList.PackingPlanNo || "").trim().length == 0) {
        that.$message.error("请填写任务单号！");
        return;
      }
      if ((that.selectedPPList.PlannedQuantity || 0) <= 0) {
        that.$message.error("请填写计划数量！");
        return;
      }
      if (!that.selectedPPList.WSType) {
        that.$message.error("请选择生产厂区！");
        return;
      }
      if (!that.selectedPPList.SegmentID) {
        that.$message.error("请选择生产车间！");
        return;
      }
      // if (!that.selectedPPList.RouteID) {
      //   that.$message.error("请选择工艺！");
      //   return;
      // }
      let sum = 0;

      that.PPList.map((i) => (sum += Number(i.PlannedQuantity)));
      if (sum != that.selectedprocedureData.Qty) {
        this.$confirm({
          title:
            "计划单数量:[" +
            sum +
            "]小于订单数量[" +
            that.selectedprocedureData.Qty +
            "]，请确认是否继续？",
          content: "",
          okText: "确认",
          okType: "danger",
          cancelText: "取消",
          async onOk() {
            await that.checkRoute();
          },
          onCancel() {
            return;
          },
        });
      } else {
        await that.checkRoute();
      }
    },
    //检验工艺
    async checkRoute() {
      let that = this;
      if (!that.selectedPPList.RouteID && that.selectedPPList.OrderType != 12) {
        this.$confirm({
          title: `没有选择工艺，请确认是否保存？`,
          content: "",
          okText: "确认",
          okType: "danger",
          cancelText: "取消",
          async onOk() {
            await that.onOKSave();
          },
          onCancel() {
            return;
          },
        });
      } else {
        await that.onOKSave();
      }
    },

    //确认保存
    async onOKSave() {
      let that = this;
      if (!that.selectedPPList.OrderType) {
        that.$message.error("请选择工单类型");
        return;
      }
      const data = {
        PackingPlanID: that.selectedPPList.PackingPlanID,
        OrderID: that.selectedPPList.OrderID,
        PackingPlanNo: that.selectedPPList.PackingPlanNo,
        PlannedQuantity: that.selectedPPList.PlannedQuantity,
        WSType: that.selectedPPList.WSType,
        SegmentID: that.selectedPPList.SegmentID,
        RouteID: that.selectedPPList.RouteID,
        Remark: that.selectedPPList.Remark,
        OrderType: that.selectedPPList.OrderType,
        UMaterialBalance: that.selectedPPList.UMaterialBalance,
        LMaterialBalance: that.selectedPPList.LMaterialBalance,
      };
      that.spinningSave = true;
      let res = await SavePacking(data);
      if (res.Status == 10000) {
        if (res.Data !== "1") {
          that.$message.error(res.Data);
        } else {
          that.$message.success("保存成功");
          that.AddPPModel = null;
          that.GetPListFun();
          that.orderShow = false;
        }
      } else {
        that.spinningSave = false;
        that.$message.error(res.Message);
      }
      that.spinningSave = false;
    },
    //下发
    async btnSend() {
      let that = this;
      if (JSON.stringify(that.selectedPPList) == "{}") {
        that.$message.error("请选择计划单");
        return;
      }
      //查询计划单关联的单号
      let resBind = await GetBindPackingPlanRelation({
        PackingPlanID: that.selectedPPList.PackingPlanID,
      });
      if (resBind.Status == 10000) {
        var str = "";
        resBind.Data.map((item, index) => {
          str += item.PackingPlanNo + ",";
        });

        if (str === "") {
          str = `当前计划单没有关联其他类型的计划单,确认下发吗？`;
        } else {
          str = `当前计划单关联【${str.substring(
            0,
            str.length - 1
          )}】,确认下发吗？`;
        }

        // that.$confirm({
        //   title: str,
        //   okText: "确认",
        //   okType: "",
        //   cancelText: "取消",
        //   async onOk() {
        //     await this.sendPlan();
        //   },
        //   onCancel() {},
        // });
        await this.sendPlan();
      } else {
        that.$message.error(res.Message);
      }
    },
    //下发操作
    async sendPlan() {
      let that = this;
      const data = {
        PackingPlanID: that.selectedPPList.PackingPlanID,
        OrderID: that.selectedPPList.OrderID,
      };
      that.loading1 = true;
      let res = await SendPacking(data);
      if (res.Status == 10000) {
        that.$message.success("下发成功");
        that.selectedPPList.State = res.Data.State;
        that.selectedPPList.AppointDt = that.dateExt.showFullDate(
          res.Data.AppointDt
        );
        that.selectedPPList.AppointUser = res.Data.AppointUser;
        that.GetPListFun();
      } else {
        that.$message.error(res.Message);
      }
      that.loading1 = false;
    },

    //反下发
    async btnSendBack() {
      let that = this;
      if (JSON.stringify(that.selectedPPList) == "{}") {
        that.$message.error("请选择计划单");
        return;
      }
      that.loading1 = true;
      const data = {
        PackingPlanID: that.selectedPPList.PackingPlanID,
        OrderID: that.selectedPPList.OrderID,
      };
      let res = await SendBackPacking(data);
      if (res.Status == 10000) {
        that.$message.success("反下发成功");
        that.selectedPPList.State = res.Data.State;
        that.selectedPPList.ModifyDt = that.dateExt.showFullDate(
          res.Data.ModifyDt
        );
        that.selectedPPList.ModifyUser = res.Data.ModifyUser;

        that.GetPListFun();
      } else {
        that.$message.error(res.Message);
      }
      that.loading1 = false;
    },
    //车间转移
    btnSegment() {
      let that = this;

      if (JSON.stringify(that.selectedPPList) == "{}") {
        that.$message.error("请选择计划单");
        return;
      }
      that.EdtiSegmentID = that.selectedPPList.SegmentID;
      that.EdtiSegmentshow = true;
    },
    //修改计划数量
    btnPlanQty() {
      let that = this;
      if (JSON.stringify(that.selectedPPList) == "{}") {
        that.$message.error("请选择计划单");
        return;
      }
      that.editPlanQtyShow = true;
    },
    //修改计划数量
    async editPalnQty() {
      let that = this;
      that.spinningSave = true;
      if (that.selectedPPList.PlannedQuantity < 0) {
        that.$message.error("请输入计划数量");
        return;
      }
      const data = {
        PackingPlanID: that.selectedPPList.PackingPlanID,
        PlannedQuantity: that.selectedPPList.PlannedQuantity,
        UMaterialBalance: that.selectedPPList.UMaterialBalance,
        LMaterialBalance: that.selectedPPList.LMaterialBalance,
        RouteID: that.selectedPPList.RouteID,
      };
      let res = await updPackingPlanByPlanQty(data);
      if (res.Status == 10000) {
        that.$message.success("修改成功！");
        that.GetPListFun();
      } else {
        that.$message.error(res.Message);
      }
      that.spinningSave = false;
      that.editPlanQtyShow = false;
    },
    //车间转移
    async EdtiSegmentOk() {
      let that = this;
      that.spinningSave = true;
      if (!that.EdtiSegmentID) {
        that.$message.error("请选择车间");
        return;
      }
      const data = {
        PackingPlanID: that.selectedPPList.PackingPlanID,
        OrderID: that.selectedPPList.OrderID,
        SegmentID: that.EdtiSegmentID,
      };
      let res = await SegmentEditPacking(data);
      if (res.Status == 10000) {
        that.$message.success("更改车间成功");

        that.GetPListFun();
      } else {
        that.$message.error(res.Message);
      }
      that.spinningSave = false;
      that.EdtiSegmentshow = false;
    },
    //关闭单据
    async btnClosePP() {
      let that = this;
      if (JSON.stringify(that.selectedPPList) == "{}") {
        that.$message.error("请选择计划单");
        return;
      }
      that.loading1 = true;
      const data = {
        PackingPlanID: that.selectedPPList.PackingPlanID,
        OrderID: that.selectedPPList.OrderID,
      };
      let res = await ClosePacking(data);
      if (res.Status == 10000) {
        that.$message.success("关闭单据成功");
        that.selectedPPList.State = res.Data.State;
        that.selectedPPList.ForcedEndDt = that.dateExt.showFullDate(
          res.Data.ForcedEndDt
        );
        that.selectedPPList.ForcedEndUser = res.Data.ForcedEndUser;
        that.PPList.splice(
          that.PPList.indexOf(that.selectedPPList),
          1,
          that.selectedPPList
        );
      } else {
        that.$message.error(res.Message);
      }
      that.loading1 = false;
    },
    //强制关闭单据
    async btnMsutClosePP() {
      let that = this;
      if (JSON.stringify(that.selectedPPList) == "{}") {
        that.$message.error("请选择计划单");
        return;
      }
      that.loading1 = true;
      const data = {
        PackingPlanID: that.selectedPPList.PackingPlanID,
        OrderID: that.selectedPPList.OrderID,
      };
      let res = await ClosePacking(data, true);
      if (res.Status == 10000) {
        that.$message.success("强制关闭单据成功");
        that.selectedPPList.State = res.Data.State;
        that.selectedPPList.ForcedEndDt = that.dateExt.showFullDate(
          res.Data.ForcedEndDt
        );
        that.selectedPPList.ForcedEndUser = res.Data.ForcedEndUser;
        that.PPList.splice(
          that.PPList.indexOf(that.selectedPPList),
          1,
          that.selectedPPList
        );
      } else {
        that.$message.error(res.Message);
      }
      that.loading1 = false;
    },
    //重启单据
    async btnReStartPP() {
      let that = this;
      if (JSON.stringify(that.selectedPPList) == "{}") {
        that.$message.error("请选择计划单");
        return;
      }
      const data = {
        PackingPlanID: that.selectedPPList.PackingPlanID,
        OrderID: that.selectedPPList.OrderID,
      };
      that.loading1 = true;
      let res = await ReStartPacking(data, true);
      if (res.Status == 10000) {
        that.$message.success("重启单据成功");
        that.selectedPPList.State = res.Data.State;
        that.selectedPPList.ModifyDt = that.dateExt.showFullDate(
          res.Data.ModifyDt
        );
        that.selectedPPList.ModifyUser = res.Data.ModifyUser;
        that.PPList.splice(
          that.PPList.indexOf(that.selectedPPList),
          1,
          that.selectedPPList
        );
      } else {
        that.$message.error(res.Message);
      }
      that.loading1 = false;
    },
    //补料
    btnReplenishment() {
      let that = this;
      that.Replenishmentshow = true;
      if (JSON.stringify(that.selectedPPList) == "{}") {
        that.$message.error("请选择计划单");
        return;
      }
      that.Replenishmentdata = {
        PackingPlanID: that.selectedPPList.PackingPlanID,
        MaterialCode: null,
        MaterialName: null,
        ComUnitName: null,
        ReqQty: null,
      };
    },
    async ReplenishmentOk() {
      let that = this;
      // if (!that.Replenishmentdata.PaRecipeDetailNo) {
      //   that.$message.info("请填写配方明细序号");
      //   return;
      // }
      if (!that.Replenishmentdata.MaterialCode) {
        that.$message.info("请填写物料编码");
        return;
      }
      if (!that.Replenishmentdata.MaterialName) {
        that.$message.info("请填写物料名称/代号");
        return;
      }
      if (!that.Replenishmentdata.ComUnitName) {
        that.$message.info("请填写计量单位名称");
        return;
      }
      if ((that.Replenishmentdata.ReqQty || 0) <= 0) {
        that.$message.info("请填写需求数量");
        return;
      }
      if ((that.Replenishmentdata.Ratio || 0) <= 0) {
        that.$message.info(
          "请填写BOM比例（如：一个半成品需要0.02kg精华液，则BOM比例是0.02；\r\n一个半成品需要1张铝模袋，则BOM比例是1）"
        );
        return;
      }
      that.spinningSave = true;
      let res = await ReplenishmentPacking(that.Replenishmentdata);
      if (res.Status == 10000) {
        that.$message.success("单据补料成功");
        that.Replenishmentshow = false;
      } else {
        that.$message.error(res.Message);
      }
      that.spinningSave = false;
    },
    //工单关联
    async btnPPRelation() {
      let that = this;
      if (JSON.stringify(that.selectedPPList) == "{}") {
        that.$message.error("请选择计划单");
        return;
      }
      that.loading1 = true;
      let res = await GetBindPackingPlanRelation({
        PackingPlanID: that.selectedPPList.PackingPlanID,
      });
      if (res.Status == 10000) {
        res.Data.map((item, index) => {
          item.num = index + 1;
          item.CreateDt = that.dateExt.showFullDate(item.CreateDt);
        });
        that.selectedPPList.bindorderList = res.Data;
        that.PPPaRelationShow = true;
      } else {
        that.$message.error(res.Message);
      }
      that.loading1 = false;
    },
    //查询工艺
    async getrouteListtomaterialCodeFun() {
      this.routeSearch.keyWords = this.selectedprocedureData.MaterialCode;
      this.routeSearch.isCheck = true;
      this.routerList = [];
      let res = await getrouteListtomaterialCode(this.routeSearch);
      this.routerFetching = false;
      if (res.Status == 10000) {
        this.routerList = this.routerList.concat(res.Data.Data);
      }
    },
  },
  created() {
    let that = this;
    that.searchItem.StartDt = that.dateExt.getDay(-60);
    that.defaulttimeList[0] = that.searchItem.StartDt;
    that.searchItem.EndDt = that.dateExt.getDay(0);
    that.defaulttimeList[1] = that.searchItem.EndDt;
    that.GetPackingPlanTypeFun();
    that.GetWorkShopTypesAllFun();
    that.GetPackingPlansListFun();
  },
  mounted() {},
  updated() {
    this.$nextTick(() => {
      this.heightid = document.getElementById("id1").offsetHeight - 90;
      this.heightids = document.getElementById("id2").offsetHeight - 34;
    });
  },
};
</script>

<style lang="less" scoped>
.operation {
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  padding: 0.5rem 1rem;
  flex: 1;
  overflow: hidden;

  .operation-search {
    display: flex;
    //justify-content: flex-end;
    border-bottom: 2px solid #f0f2f5;

    //margin-bottom: 0.9375rem;
    .selectwidth {
      width: 15rem;
    }

    .selectrightwidth {
      width: 7rem;
    }
  }

  .table-box {
    min-height: 240px;
    flex: 2;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .operation-table {
      flex: 1;
      display: flex;
      flex-direction: column;
      height: 100%;
      min-height: 240px;

      .operation-table-box {
        flex: 2;
      }
    }

    .workunit-table {
      flex: 1;
      border: 1px solid #dddddd;
      border-radius: 0.625rem;
      padding: 0.9375rem;

      .workunit-title {
        margin-bottom: 0.625rem;
      }
    }
  }

  .table-boxbelow {
    display: -webkit-flex;

    flex-direction: row;
    flex: 1.5;
    overflow: hidden;

    .operation-table {
      flex-direction: column;
      height: 100%;
      min-height: 240px;
      overflow: auto;
    }

    .workunit-table {
      border: 1px solid #dddddd;
      border-radius: 0.625rem;
      padding: 0.9375rem;

      .workunit-title {
        margin-bottom: 0.625rem;
      }
    }

    .boxleft {
      width: 100%;
    }

    .boxright {
      width: 30%;

      .fieldest-scroll {
        overflow-x: scroll;

        /deep/.ant-spin-nested-loading {
          height: 100%;

          .ant-spin-container {
            height: 100%;

            .rowpad-box {
              height: 100%;
              display: flex;
              flex-direction: column;

              .rowpad {
                flex: 1;
                display: flex;
                align-items: center;
              }
            }
          }
        }
      }
    }
  }
}

.table-paging {
  display: flex;
  justify-content: flex-end;
  margin-top: 0.5rem;
}

.fieldset {
  height: 100%;
  padding: 0.35em 0.425em 0.75em;
  margin: 0 2px;
  border: 1px solid silver;

  .legend {
    padding: 0.5em;
    border: 0;
    width: auto;
  }
}

.rowpad {
  height: 100%;
  padding: 0.25rem;
}

.procedure-modal {
  .title {
    border-bottom: 1px solid #eeeeee;
    padding: 0.625rem 0;
    margin-bottom: 0.625rem;
  }

  .production-reporting {
    border-bottom: 1px solid #eeeeee;
    padding: 0.625rem 0;
    margin-bottom: 0.625rem;

    .name {
      font-size: 1.125rem;
      font-weight: bold;
    }
  }

  .table-box {
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    min-height: 260px;

    .left {
      flex: 1;
    }

    .right {
      flex: 1;
    }

    .center {
      display: flex;
      flex-direction: column;
      margin: 0 1.25rem;
    }

    .search {
      margin: 0.625rem 0;
    }

    .name {
      font-size: 1.125rem;
      font-weight: bold;
    }
  }
}

/deep/ .ant-table-body {
  min-height: 6.25rem !important;
}
</style>
